﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Service.ActiveDirectory.Service;
using Medianamik.UI;
using Medianamik.UI.Controls;

namespace Medianamik.Service.ActiveDirectory.UI.Control
{
    public abstract class GroupsDropDownList : BaseMedianamikControl, IMedianamikControl
    {
        private readonly System.Web.UI.WebControls.DropDownList _ddList = new System.Web.UI.WebControls.DropDownList()
                                                                              {
                                                                                  ID = ControlToValidateId,
                                                                                  CssClass = "SelectList"
                                                                              };

        public BasePage BasePage
        {
            get
            {
                return (BasePage)base.Page;
            }
        }

        protected abstract IEnumerable<string> AllGroups { get; }

        public override object GetValue()
        {
            return _ddList.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value)
                .FirstOrDefault();

        }

        public override void SetValue(object value)
        {
            _ddList.SelectedValue = value.ToString();
        }

        public override System.Type TypeOfValue
        {
            get { return typeof(string); }
        }

        protected override void CreateControlHierarchy(bool pUseDataSource)
        {
            Controls.Add(_ddList);

            if (pUseDataSource)
            {
                _ddList.Items.Insert(0, string.Empty);

                var items = AllGroups.Select(n => new ListItem(n)).OrderBy(l => l.Text).ToArray();
                _ddList.Items.AddRange(items);


                var selectedValue = (DataSource ?? String.Empty).ToString();
                if (_ddList.Items.Cast<ListItem>().Any(item => item.Value.EqualsIgnoreCase(selectedValue)))
                {
                    var item = _ddList.Items.FindByValue(selectedValue);
                    if (item != null) { item.Selected = true; }
                }
            }
        }

        protected virtual void OrderItems(IList<Node> items)
        {

        }
    }
}